import axios from 'axios'
import { ElNotification } from 'element-plus'
import router from '@/router/index.ts'


// 在请求或响应被 then 或 catch 处理前拦截它们
// 添加请求拦截器
axios.interceptors.request.use(config => {
        //在发送请求之前做些什么
        //为所有请求头添加token
        if (localStorage.token) { //判断token是否存在
            config.headers.Authorization = localStorage.token; //将token设置成请求头
            // console.log(localStorage.token);
        }
        return config;
    },
    //对请求错误做些什么
    error => {
        return Promise.reject(error);
    }
);

// 添加响应拦截器
axios.interceptors.response.use(
    //对响应数据做点什么
    response => {
        let res = response.data;
        if (res.code === 200) {
            return response;
        } else if (res.code === 401) {
            ElNotification({
                title: 'Error',
                message: response.data.msg,
                type: 'error',
                duration: 2000,
            })
            router.push("/login");
            // 阻止返回
            return Promise.reject(response.data.msg);
        } else {
            console.log(res);
            ElNotification({
                    title: 'Error',
                    message: response.data.msg,
                    type: 'error',
                    duration: 2000,
                })
                // 阻止返回
            return Promise.reject(response.data.msg);
            // return response;
        }
    },
    //对响应错误做点什么
    error => {
        console.log(error);
        if (error.response.data) {
            error.message = error.response.data.msg;
        }
        if (error.response.status === 401) {
            router.push("/login");
        }
        ElNotification({
            title: 'Error',
            message: error.message,
            type: 'error',
            duration: 2000,
        })

        // 阻止返回
        return Promise.reject(error);
    }
)